package com.suse.warmstill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.suse.warmstill.common.enums.ResponseEnum;
import com.suse.warmstill.common.exception.BusinessException;
import com.suse.warmstill.entity.TbUserRole;
import com.suse.warmstill.mapper.TbUserRoleMapper;
import com.suse.warmstill.service.UserROleService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 黄靖
 * @author 2022-10-20 10:14
 * description:
 **/
@Service
public class UserROleServiceImpl implements UserROleService {
    @Autowired
    private TbUserRoleMapper userRoleMapper;

    @Override
    public List<Long> getUserIdByRoleId(Long roleId) {
        final List<Long> collect = userRoleMapper.selectList(new LambdaQueryWrapper<TbUserRole>().eq(TbUserRole::getRoleId, roleId)).stream().map(TbUserRole::getUserId).collect(Collectors.toList());

        return collect;
    }


    @Override
    public void deleteByRoleId(Long roleId) {
        final LambdaQueryWrapper<TbUserRole> tbUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tbUserRoleLambdaQueryWrapper.eq(TbUserRole::getRoleId, roleId);
        userRoleMapper.delete(tbUserRoleLambdaQueryWrapper);
    }

    @Override
    public void insert(Long id, List<Long> roleList) {
        roleList.stream().forEach((roleId) -> {
            final TbUserRole tbUserRole = new TbUserRole();
            tbUserRole.setUserId(id);
            tbUserRole.setRoleId(roleId);
            userRoleMapper.insert(tbUserRole);
        });
    }

    @Override
    public List<Long> getRoleIdByUserId(Long userId) {
        final LambdaQueryWrapper<TbUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbUserRole::getUserId, userId);

        final List<Long> roleIdsList = userRoleMapper.selectList(wrapper).stream().map(TbUserRole::getRoleId).collect(Collectors.toList());

       /* if(roleIdsList.size() == 0){
            throw new BusinessException(ResponseEnum.USER_NOROLE.getCode(),ResponseEnum.USER_NOROLE.getMsg());
        }*/
        return roleIdsList;
    }
}
